<template>
  <router-view />
</template>

<script setup>
import { provide } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
axios.defaults.baseURL = 'http://localhost:9000/'
// axios全局注入
//请求拦截器
axios.interceptors.request.use(function (config) {
  console.log('在发送请求之前做些什么')
  let token = sessionStorage.getItem('token')
  if(token){
    config.headers['token'] = token
  }
  return config
}, function (error) {
  console.log('对请求错误做些什么')
  return Promise.reject(error)
})

const router = useRouter()

//响应拦截器
axios.interceptors.response.use(function (response) {
  console.log('在响应之前做些什么')
  console.log(response);
  return response
}, function (error) {
  console.log('对响应错误做点什么')
  if(error.response.status == 401){
    router.push('/login')
  }
  return Promise.reject(error)
})

provide('axios', axios)
</script>
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

html,
body {
  height: 100%;
  margin: 0;
}
</style>
